package com.dede.monochromatism.service

import android.app.IntentService
import android.content.Intent
import com.dede.applib.util.LogExtends
import com.dede.applib.util.d
import com.dede.monochromatism.data.AppInfo
import com.dede.monochromatism.db.*
import com.dede.monochromatism.isFirst
import com.dede.monochromatism.util.Util
import org.jetbrains.anko.db.insert
import org.jetbrains.anko.db.rowParser
import org.jetbrains.anko.db.select
import org.jetbrains.anko.defaultSharedPreferences

/**
 * @author hsh
 * @date 2017/9/20 9:29.
 * @doc 加载数据库数据
 */
class DbLoaderService(name: String) : IntentService(name), LogExtends {

    constructor() : this("DbLoaderService")

    override fun onCreate() {
        super.onCreate()
        d("onCreate")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        d("onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onHandleIntent(intent: Intent?) {
        d("onHandleIntent")

        val firstIn = defaultSharedPreferences.getBoolean(isFirst, true)
        if (firstIn) {
            val defaultInputMethod = Util.getDefaultInputMethod(applicationContext)
            val inputInfo = Util.getPackageInfo(this, defaultInputMethod)
            val uiInfo = Util.getPackageInfo(this, "com.android.systemui")
            val thisInfo = Util.getPackageInfo(this, packageName)!!
            database.use {
                insert(ignoreTable, packageNameKey to thisInfo.packageName,
                        nameKey to thisInfo.applicationInfo.loadLabel(packageManager))
                if (inputInfo != null)
                    insert(ignoreTable, packageNameKey to inputInfo.packageName,
                            nameKey to inputInfo.applicationInfo.loadLabel(packageManager))
                if (uiInfo != null)
                    insert(ignoreTable, packageNameKey to uiInfo.packageName,
                            nameKey to uiInfo.applicationInfo.loadLabel(packageManager))
            }
            defaultSharedPreferences.edit().putBoolean(isFirst, false).apply()
        }

        database.use {
            PackageDb.setOpenList(
                    select(openTable)
                            .parseList(rowParser { id: Int, packageName: String, name: String, date: String ->
                                AppInfo(id, packageName, name, date)
                            })
            )
            PackageDb.setIgnoreList(
                    select(ignoreTable)
                            .parseList(rowParser { id: Int, packageName: String, name: String, date: String ->
                                AppInfo(id, packageName, name, date)
                            })
            )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        d("onDestroy")
    }
}